package com.coincalf.wallet.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.coincalf.wallet.entity.UserMemo;
import com.coincalf.wallet.mapper.UserMemoMapper;
import com.coincalf.wallet.service.UserMemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserMemoServiceImpl extends ServiceImpl<UserMemoMapper, UserMemo> implements UserMemoService {

    @Override
    public UserMemo selectOneByUserId(Long userId) {
        UserMemo userMemo = this.selectOne(new EntityWrapper<UserMemo>().eq("user_id", userId));
        if (userMemo == null) {
            //创建一个
            Long maxMemo = baseMapper.selectMaxMemo();
            if (maxMemo == null) {
                maxMemo = 0L;
            } else {
                maxMemo++;
            }
            Long maxTag = baseMapper.selectMaxTag();
            if (maxTag == null) {
                maxTag = 0L;
            } else {
                maxTag++;
            }
            userMemo = new UserMemo();
            userMemo.setUserId(userId);
            userMemo.setMemo(maxMemo);
            userMemo.setTag(maxTag);
            userMemo.setCreated(new Date());
            this.insert(userMemo);
        }
        return userMemo;
    }

    @Override
    public UserMemo selectOneByTag(Long tag) {
        UserMemo userMemo = this.selectOne(new EntityWrapper<UserMemo>().eq("tag", tag));
        if (userMemo == null) {
            log.warn("该tag未找到对应的用户 tag={}", tag);
            return null;
        } else {
            return userMemo;
        }
    }

}
